<template>
    <el-drawer
        ref="drawRef"
        class="reset"
        v-model="dialogVisible"
        :title="'新增日日保报案'"
        :destroy-on-close="true"
        @close="handleClose"
        :size="isMobile ? '100%' : 750"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
        <div class="w-full box-border p-16px">
            <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-position="top"
                class=""
            >
                <div class="grid gap-10px">
                    <el-form-item
                        :class="[i.width]"
                        v-for="(i, index) in formData"
                        :key="index"
                        :label="i.label"
                        :prop="`${i.prop}.value`"
                    >
                        <el-select
                            v-if="i.type === 'select'"
                            class="w-full"
                            v-model="i.value"
                            :filterable="i.filterable"
                            :remote="i.remote"
                            :placeholder="i.placeholder"
                            :disabled="i.disabled"
                            :remote-method="($event) => i.remoteMethod($event, i)"
                            @focus="i.handleFocus && i.handleFocus(i)"
                            @change="i.handleChange && i.handleChange(i)"
                        >
                            <el-option
                                v-for="item in i.options"
                                :key="item[i.defaultAttrs.value]"
                                :label="item[i.defaultAttrs.label]"
                                :value="item[i.defaultAttrs.value]"
                                :filterable="i.filterable"
                            />
                        </el-select>

                        <el-date-picker
                            v-if="i.type === 'date'"
                            :ref="(el) => createElDateRef(el, i.prop)"
                            class="reset-date w-full"
                            v-model="i.value"
                            :type="i.dateType || 'date'"
                            :placeholder="i.placeholder"
                            :disabled="i.disabled"
                            :disabled-date="i.disableDate"
                            :value-format="i.valueFormat || 'YYYY-MM-DD'"
                        />
                        <el-input
                            v-if="i.type === 'input'"
                            class="w-full"
                            v-model="i.value"
                            :maxlength="i.maxlength"
                            :type="i.inputType || 'text'"
                            :placeholder="i.placeholder"
                        />

                        <el-input
                            v-if="i.type === 'textarea'"
                            class="w-full"
                            v-model="i.value"
                            :maxlength="i.maxlength || 500"
                            :placeholder="i.placeholder"
                            show-word-limit
                            type="textarea"
                        />
                        <uploadVideo v-if="i.type === 'upload'" v-model="i.value" />
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="flex flex-jc-c">
                <el-button type="primary" plain @click="submit">提交</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { cloneDeep } from 'lodash'
import {
    exportImagesLong,
    getMaterialsLong,
    addMaterialsLong,
    removeMaterialsLong,
    exportImagesDay,
    getMaterialsDay,
    addMaterialsDay,
    removeMaterialsDay,
} from '@/api/clients/index.ts'
import { useStore } from '@/store/index.ts'
import uploadVideo from '@/components/uploadVideo/index.vue'
import { getCompanyByName } from '@/api/tools/blackList.ts'
import { outDangerUserInfo, reportCaseDay } from '@/api/reportClaimAdjuster/addCase.ts'
import dayjs from 'dayjs'
const store = useStore()
const isMobile = ref(window.isMobile)

const drawRef = ref(null)

const formRef = ref(null)

const elDateRefs = ref({})

const previewList = ref([])

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    curItem: {
        type: Object,
    },
    insureType: {
        type: String,
    },
})

const emits = defineEmits(['update:show', 'success'])

const dialogVisible = ref(false)

const formData = ref({
    companyId: {
        label: '报案公司',
        prop: 'companyId',
        type: 'select',
        placeholder: '请输入报案公司名称',
        value: '',
        filterable: true,
        remote: true,
        remoteMethod: (ev, item) => {
            if (!ev) return
            getCompanyByName({
                auditStatus: 1,
                companyName: ev,
            }).then((res) => {
                item.options = res || []
                item.options.forEach((i) => {
                    i.companyName = i.superAdminUserName
                        ? i.companyName + `(${i.superAdminUserName})`
                        : i.companyName
                })
            })
        },
        options: [],
        defaultAttrs: {
            label: 'companyName',
            value: 'id',
        },
        width: 'full',
        handleChange: (item) => {
            formData.value.insureCompanyType.value = ''
            formData.value.insureCompanyType.handleChange()
        },
    },
    params: {
        label: '上传受伤者视频',
        prop: 'params',
        type: 'upload',
        value: [],
        width: 'full',
    },
    insureCompanyType: {
        label: '保险类型',
        type: 'select',
        prop: 'insureCompanyType',
        placeholder: '请选择出险类型',
        skip: true,
        value: '',
        options: [
            {
                label: '团意险',
                value: 'insure_type_tyrb',
            },
            {
                label: '日日保',
                value: 'insure_type_rrb',
            },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
        handleChange: () => {
            formData.value.recordId.value = ''
            formData.value.recordId.options = []
            formData.value.insureDay.value = ''
            formData.value.outDangerDate.value = ''
        },
    },
    recordId: {
        label: '出险人',
        type: 'select',
        prop: 'recordId',
        placeholder: '请选择出险人',
        value: '',
        params: {
            outDangerUserName: '',
            outDangerUserId: '',
            idCardNo: '',
        },
        options: [],
        defaultAttrs: {
            label: 'outDangerUserName',
            value: 'id',
        },
        width: 'half',
        filterable: true,
        remote: true,
        remoteMethod: (ev, item) => {
            if (!ev) return
            if (!formData.value.companyId.value) {
                ElMessage.error('请先选择报案公司')
                return
            }
            if (!formData.value.insureCompanyType.value) {
                ElMessage.error('请先选择保险类型')
                return
            }
            outDangerUserInfo(
                {
                    outDangerUserName: ev,
                    isQueryOutDanger: 0,
                    insureCompanyType: formData.value.insureCompanyType.value,
                    companyId: formData.value.companyId.value,
                },
                {
                    noLoading: true,
                }
            ).then((res) => {
                item.options = res || []
                item.options.forEach((i) => {
                    i.outDangerUserName =
                        i.userName +
                        '（' +
                        i?.idCardNo?.substring(14) +
                        '）' +
                        '投保时间:' +
                        i.createTime
                })
            })
        },
        handleChange: (item) => {
            formData.value.outDangerDate.value = ''
            const curOption = item.options.find((i) => i.id === item.value)
            if (curOption) {
                formData.value.insureDay.value = curOption.createTime
                item.params.outDangerUserName = curOption.userName
                item.params.outDangerUserId = curOption.userId
                item.params.idCardNo = curOption.idCardNo
                formRef.value.validateField('insureDay.value')
            }
        },
    },
    insureDay: {
        label: '投保时间',
        type: 'date',
        prop: 'insureDay',
        placeholder: '请选择投保时间',
        value: '',
        width: 'half',
        disabled: true,
        skip: true,
    },
    outDangerPhone: {
        label: '出险人手机号',
        type: 'input',
        prop: 'outDangerPhone',
        placeholder: '请输入手机号',
        value: '',
        width: 'half',
        maxlength: 11,
        inputType: 'tel',
    },
    outDangerDate: {
        label: '出险时间',
        type: 'date',
        prop: 'outDangerDate',
        placeholder: '请选择出险时间',
        value: '',
        width: 'half',
        disableDate: (time) => {
            const start = dayjs(
                dayjs(formData.value.insureDay.value).format('YYYY-MM-DD') + ' 00:00::00'
            ).valueOf()
            const end = dayjs(formData.value.insureDay.value).add(1, 'day').valueOf()
            return time.getTime() < start || time.getTime() > end
        },
    },
    hurtStatus: {
        label: '是否有骨折或更严重伤情',
        type: 'select',
        prop: 'hurtStatus',
        placeholder: '请选择',
        value: '',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 2,
            },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    hospitalStatus: {
        label: '是否住院',
        type: 'select',
        prop: 'hospitalStatus',
        placeholder: '请选择',
        value: '',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 2,
            },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    accidentType: {
        label: '事故类型',
        type: 'select',
        prop: 'accidentType',
        placeholder: '请选择事故类型',
        value: '',
        options: [
            {
                label: '意外',
                value: 1,
            },
            {
                label: '工伤',
                value: 2,
            },
        ],
        defaultAttrs: {
            label: 'label',
            value: 'value',
        },
        width: 'half',
    },
    outDangerPlace: {
        label: '出险地点',
        type: 'input',
        prop: 'outDangerPlace',
        placeholder: '请输入出险地点，如xx公司xx车间',
        value: '',
        width: 'full',
    },
    visitHospital: {
        label: '就诊医院',
        type: 'input',
        prop: 'visitHospital',
        placeholder: '如：昆山市第一人民医院',
        value: '',
        width: 'full',
    },
    accidentDetails: {
        label: '详细事故经过',
        type: 'textarea',
        prop: 'accidentDetails',
        placeholder: '请输入详细事故经过',
        value: '',
        width: 'full',
    },
    reportPhone: {
        label: '报案人电话',
        type: 'input',
        prop: 'reportPhone',
        placeholder: '请输入报案人电话',
        value: '',
        width: 'full',
    },
})

const rules = ref({
    'companyId.value': [
        {
            required: true,
            trigger: 'change',
            message: '请输入报案公司名称',
        },
    ],
    'insureCompanyType.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择出险类型',
        },
    ],
    'recordId.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择出险人',
        },
    ],
    'insureDay.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择投保时间',
        },
    ],
    'outDangerPhone.value': [
        {
            required: true,
            trigger: 'change',
            message: '请输入出险人手机号',
        },
    ],
    'outDangerDate.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择出险时间',
        },
    ],
    'hurtStatus.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择是否有骨折或更严重伤情',
        },
    ],
    'hospitalStatus.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择是否住院',
        },
    ],
    'accidentType.value': [
        {
            required: true,
            trigger: 'change',
            message: '请选择事故类型',
        },
    ],
    'outDangerPlace.value': [
        {
            required: true,
            trigger: 'blur',
            message: '请输入出险地点',
        },
    ],
    'visitHospital.value': [
        {
            required: true,
            trigger: 'blur',
            message: '请输入就诊医院',
        },
    ],
    'accidentDetails.value': [
        {
            required: true,
            trigger: 'blur',
            message: '请输入详细事故经过',
        },
    ],
    'reportPhone.value': [
        {
            required: true,
            trigger: 'blur',
            message: '请输入报案人电话',
        },
    ],
})
const createElDateRef = (el, prop) => {
    if (el) {
        elDateRefs.value[prop] = el
    }
}

const handleClose = (done) => {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    formData.value.companyId.options = []
    formData.value.recordId.options = []
    dialogVisible.value = false
}

const createQuery = () => {
    const params = {
        isAdmin: 1,
    }
    for (const key in formData.value) {
        if (!formData.value[key].skip) {
            params[formData.value[key].prop] = formData.value[key].value
            if (formData.value[key].params) {
                Object.assign(params, formData.value[key].params)
            }
        }
    }
    const temps = params.params
    params.params = {}
    params.params.photos = temps
    return params
}

const submit = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            reportCaseDay({
                ...createQuery(),
            }).then((res) => {
                handleClose()
                emits('success')
            })
        } else {
            console.log('error', fields)
        }
    })
}

watch(
    () => props.show,
    (newval) => {
        dialogVisible.value = newval
        if (newval) {
            // getData()
        }
    }
)

watch(dialogVisible, (newval) => {
    emits('update:show', newval)
    if (!newval) {
        // formRef.value.resetFields()
    }
})
</script>
<style lang="scss" scoped>
.header {
    &::before {
        content: "";
        border-left: 4px solid #0256ff;
        height: 14px;
        margin-right: 5px;
    }
}

.grid {
    display: flex;
    flex-wrap: wrap;
}

.full {
    flex-basis: calc(100% - 10px);
}

.half {
    flex-basis: calc(50% - 10px);
}

:deep(.reset-date .el-input__wrapper) {
    // display: flex;
    width: calc(100% - 20px) !important;
}

:deep(.reset-card .el-upload--picture-card) {
    justify-content: start;
    background: #fff;
}

:deep(.reset-card .el-upload-list__item) {
    width: 72px;
    height: 72px;
}

:deep(.reset .el-drawer__header) {
    margin-bottom: 0;
}
</style>
